package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.eventbus.HasNewEvent;
import com.asktgapp.hxsg.BiuEaseHelper;
import com.asktgapp.model.DifferentTypeVO;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.user.activity.ConsultationActivity;
import com.asktgapp.user.activity.QuestionActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 2018年7月31日 10:25:50
 * Description: 新我的咨询页面 table页面
 */

public class ConsultNewFragment extends BaseFragment {

    @InjectView(R.id.questionAndAnswer)
    LinearLayout questionAndAnswer;
    @InjectView(R.id.consultation)
    LinearLayout consultation;

    @InjectView(R.id.questionAndAnswerMessageNumber)
    TextView questionAndAnswerMessageNumber;
    @InjectView(R.id.ivQuestionAndAnswer)
    ImageView ivQuestionAndAnswer;
    @InjectView(R.id.tvQuestionAndAnswer)
    TextView tvQuestionAndAnswer;

    @InjectView(R.id.consultationMessageNumber)
    TextView consultationMessageNumber;
    private boolean readAll = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_consult_new, container, false);
        ButterKnife.inject(this, viewGroup);
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {


        questionAndAnswer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), QuestionActivity.class));
                if (readAll)
                    changeToRead();
            }
        });

        consultation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), ConsultationActivity.class));
            }
        });

        if (!MyApplication.userIdIsEmpty(getContext())) {
            EMConnectionListener connectionListener = new EMConnectionListener() {
                @Override
                public void onConnected() {
                }

                @Override
                public void onDisconnected(final int error) {
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        doDisconnected(error);
//                    }
//                });
//
                }
            };
            EMClient.getInstance().addConnectionListener(connectionListener);

        }

    }

    public void doDisconnected(int error) {
        if (error == EMError.USER_REMOVED) {

        } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
//            Toast.makeText(this, "帐号在其他设备登录", Toast.LENGTH_SHORT).show();
        } else if (error == EMError.SERVER_SERVICE_RESTRICTED) {
            BiuEaseHelper.loginOut();
        } else {
            BiuEaseHelper.reset();
        }
    }

    @Override
    public void loadData() {
        if (!TextUtils.isEmpty(PreferencesUtil.getString(getContext(), PreferencesUtil.USER_ID))
                && PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER))
            differentType();
    }

    //问答相关消息接口
    private void differentType() {

        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userId", PreferencesUtil.getString(getContext(), PreferencesUtil.USER_ID));
//        params.put("platform", "0");
//        params.put("deviceId", Utils.getDeviceId(MyApplication.getInstance()));
        params.put("page", 1);
//        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody<DifferentTypeVO>> call = apiservice.differentType(params);
        call.enqueue(new Callback<ApiResponseBody<DifferentTypeVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<DifferentTypeVO>> call, Response<ApiResponseBody<DifferentTypeVO>> response) {
//                dismissProgress();
                if (response.isSuccessful()) {
                    DifferentTypeVO bean = response.body().getResult();
                    if (bean != null) {
                        if (bean.getIsNotReadNum() > 0) {
//                            HasNewEvent.postEvent(1);
                            readAll = true;
                            questionAndAnswerMessageNumber.setText(String.valueOf(bean.getIsNotReadNum()));
                            ImageDisplayUtil.loadCircleHeadImage(getActivity(), ivQuestionAndAnswer, bean.getUserPic());
                            tvQuestionAndAnswer.setText(bean.getUserName());
                            questionAndAnswerMessageNumber.setVisibility(View.VISIBLE);
                            ivQuestionAndAnswer.setVisibility(View.VISIBLE);
                        } else {
//                            HasNewEvent.postEvent(0);
                            readAll = false;
                            tvQuestionAndAnswer.setText("");
                            questionAndAnswerMessageNumber.setVisibility(View.INVISIBLE);
                            ivQuestionAndAnswer.setVisibility(View.INVISIBLE);

                        }

                    }
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<DifferentTypeVO>> call, Throwable t) {
//                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

    //问答相关消息标记已读接口
    private void changeToRead() {

        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userId", PreferencesUtil.getString(getContext(), PreferencesUtil.USER_ID));
//        params.put("platform", "0");
//        params.put("deviceId", Utils.getDeviceId(MyApplication.getInstance()));
        params.put("page", 1);
//        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody<DifferentTypeVO>> call = apiservice.changeToRead(params);
        call.enqueue(new Callback<ApiResponseBody<DifferentTypeVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<DifferentTypeVO>> call, Response<ApiResponseBody<DifferentTypeVO>> response) {
                dismissProgress();
//                if (response.isSuccessful()) {
//                    loadData();
//                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<DifferentTypeVO>> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.reset(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void hasNewMsg(HasNewEvent event) {
        if (event.getType() == 5) {
            consultationMessageNumber.setVisibility(View.GONE);
        } else if (event.getType() == 6) {
            consultationMessageNumber.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }
}
